import { isString } from 'lodash-es'
import { RouteLocationRaw, Router } from 'vue-router'
import { decrypt, encrypt } from '../utils/encrypt'

/**
 * eg:
 * 1、页面跳转并query加密
 *  const router = useEncryptRouter()
 *  router.push({
 *    name: 'DictDataList',
 *    query: {
 *      id: '007',
 *    }
 *  })
 *
 * 2、获取当前路由query
 * 1）方式一：query不带验证
 *  const router = useEncryptRouter()
 *  const { id } = router.getQuery()
 *
 * 2）方式二：query带验证
 * const { id } = await getRouteQuery<{ id: string }>(['id'], { isEncrypt: true })
 *
 * 注意： 只支持push replace跳转的query加密！！！
 */

export const useEncryptRouter = () => {
  const _router: Router = useRouter()

  const handle = (to: RouteLocationRaw, mode: 'push' | 'replace') => {
    if (!isString(to) && to.query) {
      return _router[mode]({
        ...to,
        query: {
          query: encrypt(to.query)
        }
      })
    } else {
      return _router[mode](to)
    }
  }

  const getQuery = () => {
    try {
      const _query = _router.currentRoute.value?.query?.query
      if (_query) {
        const queryString = decrypt(_query)
        return JSON.parse(queryString)
      }
      return {}
    } catch (error) {
      console.log(error)
    }
  }

  const router: Router & {
    getQuery: (isValid?: boolean) => Record<string, any>
  } = {
    ..._router,
    push: (to: RouteLocationRaw) => handle(to, 'push'),
    replace: (to: RouteLocationRaw) => handle(to, 'replace'),
    getQuery
  }

  return router
}
